package com.hm.PushCaseService.service.ydcg.caseinfo.info;

import com.alibaba.fastjson2.JSON;
import com.hm.PushCaseService.pojo.CaseRespBean;
import com.hm.PushCaseService.pojo.ydcg.ReqCaseParamsBean;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

/**
 * 获取案件信息
 */

@Service
public class CaseInfoService implements ICaseInfo {

    private static final Logger logger = LoggerFactory.getLogger(CaseInfoService.class);
    private static final int pageSize = 100;//每页展示案件的数量

    @Qualifier("OkHttpClient")
    public OkHttpClient okHttpClient;

    public CaseInfoService(OkHttpClient okHttpClient) {
        this.okHttpClient = okHttpClient;
    }

    @Override
    public CaseRespBean getCaseInfo(String startTime, String endTime, int pageIndex, String token, String reqUrl) {
        ReqCaseParamsBean paramsBean = new ReqCaseParamsBean();
        paramsBean.start_time = startTime;//开始时间
        paramsBean.end_time = endTime;//结束时间
        paramsBean.pageIndex = pageIndex;//页码
        paramsBean.pageSize = pageSize;//每页展示的数量
        //开始请求
        String reqParams = JSON.toJSONString(paramsBean);
        //构建请求体
        RequestBody body = RequestBody.create(reqParams, MediaType.get("application/json; charset=UTF-8"));
        Request request = new Request.Builder()//
                .addHeader("Authorization", "bearer " + token)//token认证
                .url(reqUrl)//请求连接
                .post(body)//请求体
                .build();//构建
        //同步请求
        try (Response response = okHttpClient.newCall(request).execute()) {
            ResponseBody responseBody = response.body();
            if (responseBody == null) {
                return null;
            }
            String jsonString = responseBody.string();
            CaseRespBean caseRespBean = JSON.parseObject(jsonString, CaseRespBean.class);
            if (caseRespBean == null) {
                return null;
            }
            int totalCount = caseRespBean.totalCount;
            //计算有多少页-->totalPages根据每页展示的数量变化
            caseRespBean.totalPages = (totalCount + pageSize - 1) / pageSize;
            return caseRespBean;
        } catch (Exception e) {
            logger.error("获取案件信息Exception: " + e.getMessage());
        }
        return null;
    }
}
